﻿using System;
using System.IO;
using System.Collections.Generic;

using Flagwind.Services;
using Flagwind.Resources;

namespace Flagwind.Utilities
{
	internal class Program
	{
		public static void Main(string[] args)
		{
			if(args == null || args.Length < 1)
			{
				Console.WriteLine(ResourceUtility.GetString("Text.MissingArguments"));
				return;
			}

			try
			{
				//使用当前命令行参数构造一个命令表达式
				var expression = CommandExpression.Parse("deployer " + string.Join(" ", args));

				//创建一个部署文件路径的列表
				var paths = new List<string>(expression.Arguments.Length);

				//校验所有指定的文件路径是否都存在，并将处理后的路径加入到待处理的列表中
				foreach(var argument in expression.Arguments)
				{
					var path = Path.IsPathRooted(argument) ? argument : Flagwind.IO.Path.Combine(Environment.CurrentDirectory, argument);

					if(File.Exists(path))
						paths.Add(path);
					else
						throw new FileNotFoundException(path);
				}

				//创建部署器类的实例
				var deployer = new Deployer(new Flagwind.Terminals.ConsoleTerminal());

				//将命令行选项添加到部署器的环境变量中
				if(expression.Options.Count > 0)
				{
					foreach(var option in expression.Options)
					{
						deployer.EnvironmentVariables[option.Key] = option.Value;
					}
				}

				//依次部署指定的部署文件
				foreach(var path in paths)
				{
					//部署指定的文件
					var counter = deployer.Deploy(path);

					//打印部署的结果信息
					deployer.Terminal.WriteLine(CommandOutletColor.DarkGreen, ResourceUtility.GetString("Text.Deploy.CompleteInfo", path, counter.Total, counter.Successes, counter.Failures));
				}
			}
			catch(Exception ex)
			{
				//设置控制台前景色为“红色”
				var foregroundColor = Console.ForegroundColor;
				Console.ForegroundColor = ConsoleColor.Red;

				//打印异常消息
				Console.Error.WriteLine(ex.Message);

				//重置控制台的前景色
				Console.ForegroundColor = foregroundColor;
			}
		}
	}
}
